package com.seka.control.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Component;

import com.seka.control.common.SekaContants;
import com.seka.control.dto.SekaResponse;
import com.seka.control.service.SekaControl;
import com.seka.control.utils.JsonUtil;
import com.seka.control.utils.SekaSpringContextHolder;

@Component
//@WebFilter(servletNames = "sekaFilter",urlPatterns = SekaContants.SEKA_MONITOR_URL)
public class SekaFilter implements Filter{

	
	private SekaControl sekaControl;
	
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest)request;
		if(req.getRequestURI().contains(SekaContants.SEKA_MONITOR_URL)){
			out(response);
			return ;
		}
		chain.doFilter(request, response);
	}

	/**
	 * 输出
	 * @param response
	 */
	private void out(ServletResponse response) {
		ServletOutputStream outputStream =null;
		try {
			outputStream = response.getOutputStream();
			SekaResponse res = new SekaResponse(true, get().getSeka());
			outputStream.write(JsonUtil.toJSONString(res).getBytes());
			outputStream.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			try {
				if(outputStream !=null) {
					outputStream.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
	
		}
		
	}
	
	/**
	 * 获取 SekaControl 对象
	 * @return SekaControl
	 */
	public SekaControl get() {
		if(sekaControl ==null) {
			sekaControl =  SekaSpringContextHolder.getBean(SekaControl.class);
		}
		return sekaControl;
	}

}
